package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-02-08
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    @Transactional
    public void importSubjectData(MultipartFile file, EduSubjectService subjectService) {
        //添加课程分类
        InputStream inputStream = null;
        try {
            //文件输入流
            inputStream = file.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //调用方法进行读取
        EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();

    }

    @Override
    public List<OneSubject> getAllTree() {
        QueryWrapper<EduSubject> one = new QueryWrapper<>();
        one.eq("parent_id", "0");
        List<EduSubject> list = this.list(one);
        List<OneSubject> parent = diGui(list);
        return parent;
    }

    private List<OneSubject> diGui(List<EduSubject> list) {
        List<OneSubject> parent = new ArrayList<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                OneSubject oneSubject = new OneSubject();
                EduSubject eduSubject = list.get(i);
                String id = eduSubject.getId();
                String title = eduSubject.getTitle();
                oneSubject.setId(id);
                oneSubject.setTitle(title);
                //查children
                QueryWrapper<EduSubject> two = new QueryWrapper<>();
                two.eq("parent_id", id);
                List<EduSubject> twoList = this.list(two);
                List<OneSubject> children = diGui(twoList);
                oneSubject.setChildren(children);
                parent.add(oneSubject);
            }
        }
        return parent;
    }


}
